package com.sq.system.base;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Test {

    private static final String API_KEY = "9fe97b4cee64d984487e9d907577b52d";
    private static final String URL = "https://restapi.amap.com/v3/ip?key=%s";
    public static void getLocationByIP() throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(String.format(URL, API_KEY)))
                .build();
        // 解析JSON响应示例（建议使用Jackson/Gson）
        //                    String[] parts = response.split("\"");
        //                    if(parts) {
        //                        Double lon = Double.parseDouble(extractValue(parts, "rectangle", 3)); // 经度
        //                    }
        //
        //                    Double lat = Double.parseDouble(extractValue(parts, "rectangle", 1));  // 纬度
        //                    System.out.printf("网络定位结果：经度=%f, 纬度=%f%n", lon, lat);
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println).join();
    }
    // 简易JSON字段提取（生产环境建议用JSON库）
    private static String extractValue(String[] parts, String key, int offset) {
        for (int i = 0; i < parts.length; i++) {
            if (parts[i].contains(key)) {
                return parts[i + offset].replaceAll("[^\\d.]", "");
            }
        }
        return "0";
    }
    public static void main(String[] args) {
        try {
            getLocationByIP();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
